package com.example.demo;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.*;
import java.text.MessageFormat;
import java.util.Scanner;

public class jdbc2 {
    public static void main(String[] args) {
        // 定义MySQL数据源对象
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        // 设置数据库连接串
        mysqlDataSource.setURL("jdbc:mysql://127.0.0.1:3306/studyroom?characterEncoding=utf8" +
                "&allowPublicKeyRetrieval=true&useSSL=false");
        // 用户名
        mysqlDataSource.setUser("root");
        // 密码
        mysqlDataSource.setPassword("123456");

        // 定义JDBC的数据源对象
        DataSource dataSource = mysqlDataSource;

        // 定义连接对象
        Connection connection = null;
        // 定义预处理SQL执行对象
        PreparedStatement statement = null;
        // 定义结果集对象
        ResultSet resultSet = null;

        try {
            // 1. 通过数据源获取数据库连接
            connection = dataSource.getConnection();
            // 2. 获取预处理SQL执行对象
            //输入
            System.out.println("请输入学生编号：");
            Scanner scanner = new Scanner(System.in);
            int id = scanner.nextInt();
            // 定义要执行的SQL
            String sql = "select user_id, username, password, phone, email, school, points from users where user_id = ?";
            statement = connection.prepareStatement(sql);
            // 3. 用真实值替换占位符
            statement.setInt(1, id);
            // 4. 执行SQL,获取结果集
            resultSet = statement.executeQuery();
            // 5. 遍历结果集
            while (resultSet.next()) {
                // 获取学生Id
                long user_id = resultSet.getLong(1);
                String username = resultSet.getString(2);
                String password = resultSet.getString(3);
                String phone = resultSet.getString(4);
                String email = resultSet.getString(5);
                String school = resultSet.getString(6);
                long points= resultSet.getLong(7);
                System.out.println(MessageFormat.format("学生编号={0}, 姓名={1}, 密码={2}, 手机号={3}, 邮箱={4}, 学校={5}, 点数={6}", user_id, username, password, phone
                        , email, school, points));
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 依次释放资源，关闭连接
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
